import * as Cesium from 'cesium';
import HeatMapLayer from '@cesium-extends/heat';
import h337 from 'heatmap.js';
import CesiumHeatmap from "@/utils/CesiumHeatmap";
import modifyMap from "@/utils/filterColor";
import { Spriteline1MaterialProperty } from '@/utils/Spriteline.js'
// import '/public/airMonitor/CesiumNetworkPlug.min.js'
import localforage from "localforage";
import CircleRippleMaterialProperty from "@/utils/material/CircleRippleMaterialProperty.js"
// import CloudEffectMaterial from "@/utils/cloudEffectMaterial";
//在class外 定义viewer由于有些方法在this.viewer中使用会失效
// window.Cesium = Cesium
// window.localforage = localforage
// window.localforage = localforage
var viewer = undefined
let handler = null;
let entityPosition = null;
let heatMap = null;
let nephogramEntity = null;
let perspectiveEntity = null;
let dataRoad = null;
let titlesObj = null;
var curCanvas = 'a';
let cockpitFun;
let viewDefaultFun;
let changeCheckCockpit;
let clickWaringDis;
let clickWaringDisTrue;
let modelThree = {
  bulid: [],
  road: [],
} // 三维模型
class cesium {
  domId = "cesiumContainer" //页面定义div id
  viewer = null  //viewer对象
  handler = null //cesium一些事件对象
  setting = { //cesium地图初始化一些基础配置
    animation: false, //是否显示动画控件
    baseLayerPicker: false, //是否显示图层选择控件
    geocoder: false, //是否显示地名查找控件
    timeline: true, //是否显示时间线控件
    sceneModePicker: false, //是否显示投影方式控件
    navigationHelpButton: false, //是否显示帮助信息控件
    fullscreenButton: false,
    homeButton: false,
    scene3DOnly: false, //仅仅显示3d,可隐藏右上角2d和3d按钮
    selectionoIndicatr: false,
    initNoFlyTo: false,//地图初始化完成是否飞向默认视角
    infoBox: false, // 是否显示点击要素之后显示的信息
    selectionIndicator: false, // 要素选中框
    shouldAnimate: true, // 必须为true开启动画 否则不会达到飞机模型飞行动画效果
  }

  constructor(config, domId, openPop, viewDefault) {
    cockpitFun = openPop;
    viewDefaultFun = viewDefault;
    Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmYjMxMzNiMC01Y2I3LTRlZDYtODZmYS1iNjE3ZWRmNTcxMDUiLCJpZCI6MTcyNzUsImlhdCI6MTcwMTc0ODQ5M30.NFQD24HPgC-34__kwexQK6bdgwJKxJwdBex_BlxvZpE";
    this.domId = domId
    this.setting = Object.assign(config || {}, this.setting)
    this.init()
  }

  // 获取地图对象
  getMapViewer(viewObject) {
    viewObject(viewer)
  }

  // 初始化地图
  init() {
    // 添加 IndexDB 缓存规则
    // const OfflineCacheController = CesiumNetworkPlug.OfflineCacheController
    // ① 全局缓存
    // OfflineCacheController.ruleList.add('*')
    // console.log("-------------                              -------------------------", CesiumNetworkPlug.OfflineCacheController)

    viewer && viewer.destroy()
    viewer = new Cesium.Viewer(this.domId || 'cesiumContainer', this.setting)
    this.viewer = viewer
    window.viewer = viewer;
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)

    handler.setInputAction(function (evt) {
      var ray = viewer.camera.getPickRay(evt.position);
      var cartesian = viewer.scene.globe.pick(ray, viewer.scene);
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      var lng = Cesium.Math.toDegrees(cartographic.longitude);//经度值
      var lat = Cesium.Math.toDegrees(cartographic.latitude);//纬度值
      // var mapPosition = { x: lng, y: lat, z: cartographic.height };//cartographic.height的值为地形高度。
      console.log("获取经纬度", lng, lat)
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    handler.setInputAction(function (movement) {
      var pickedObject = viewer.scene.pick(movement.endPosition);
      var element = viewer.canvas;
      // viewDefaultFun();
      if (
        Cesium.defined(pickedObject) &&
        Cesium.defined(pickedObject.id) &&
        Cesium.defined(pickedObject.id.cursorHand)
      ) {
        element.style.cursor = "pointer";
      } else {
        element.style.cursor = "default";
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    // viewer.scene.postRender.addEventListener(function(){
    //   console.log("拖拽了！")
    // })

    handler.setInputAction(function (event) {
      viewDefaultFun();
    }, Cesium.ScreenSpaceEventType.WHEEL);

    handler.setInputAction(function (event) {
      viewDefaultFun();
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

    this.setDrawHandler();

    document.querySelector('.cesium-widget-credits').style.display = 'none'
    viewer.scene.globe.depthTestAgainstTerrain = false
    viewer._cesiumWidget._creditContainer.style.display = 'none' // 去除logo

    const utc = Cesium.JulianDate.fromDate(new Date('2021/07/04 05:00:00'))

    viewer.clockViewModel.currentTime = Cesium.JulianDate.addHours(utc, 8, new Cesium.JulianDate())

    /* 自建离线地图 */
    /* 地图配置 */
    let option = {
      // url: `http://t0.tianditu.gov.cn/cva_w/wmts?tk=4999d7c944e5f23def8cff1e1e7b880b`,
      url: "http://211.90.240.63:6018/geoserver/zhejiang/gwc/service/wmts",
      // url: 'http://www.zjjnks.cn/geoserver/keyunit/gwc/service/wmts',
      // url: 'http://www.zjjnks.cn/geoserver/xihu/gwc/service/wmts',
      format: "image/png",
      style: "", //务必加上style属性，哪怕style属性值为空字符串！！！！
      tileMatrixSetID: "EPSG:4326",
      tileMatrixLabels: [
        "EPSG:4326:0",
        "EPSG:4326:1",
        "EPSG:4326:2",
        "EPSG:4326:3",
        "EPSG:4326:4",
        "EPSG:4326:5",
        "EPSG:4326:6",
        "EPSG:4326:7",
        "EPSG:4326:8",
        "EPSG:4326:9",
        "EPSG:4326:10",
        "EPSG:4326:11",
        "EPSG:4326:12",
        "EPSG:4326:13",
        "EPSG:4326:14",
        "EPSG:4326:15",
        "EPSG:4326:16",
        "EPSG:4326:17",
        "EPSG:4326:18",
      ],
      tilingScheme: new Cesium.GeographicTilingScheme(),
      maximumLevel: 18,
    };
    /* 卫星地图 */
    let satelliteMap18 = new Cesium.WebMapTileServiceImageryProvider({
      layer: "zhejiang:zjszf_wx_Level_18",
      ...option,
    });
    let satelliteMap15 = new Cesium.WebMapTileServiceImageryProvider({
      layer: "zhejiang:zjszf_wx_Level_15",
      ...option,
    });
    let satelliteMap13 = new Cesium.WebMapTileServiceImageryProvider({
      layer: "zhejiang:zjszf_wx_Level_13",
      ...option,
    });

    // viewer.imageryLayers.addImageryProvider(satelliteMap18);
    // viewer.imageryLayers.addImageryProvider(satelliteMap15);
    // viewer.imageryLayers.addImageryProvider(satelliteMap13);

    // viewer.imageryLayers.get(0).show = false
    // viewer.imageryLayers.get(1).show = false;
    // viewer.imageryLayers.get(2).show = false;
    // 获取当前高度
    // viewer.scene.globe.ellipsoid.cartesianToCartographic(viewer.camera.position).height
    // 最小缩放高度（米）
    viewer.scene.screenSpaceCameraController.minimumZoomDistance = 50;
    // 最大缩放高度（米）
    // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 100000;
    /* 启用场景照明 */
    viewer.scene.globe.enableLighting = true;

    /* 设置相机位置 */
    viewer.camera.setView({
      // 设置相机位置
      destination: {
        x: -2789575.5099842506,
        y: 4801085.598874651,
        z: 3170177.394385061
        // x: -2769035.8008190286,
        // y: 4771116.686931403,
        // z: 3194171.2282843282
      },
      orientation: {
        // 初始视角
        heading: 6.238757102061567,
        pitch: -0.5230891552682251,
        roll: 0.000030715561083027865,
      },
    });

    const { scene } = viewer
    // 设置鼠标滚轮进行视图 zoom 变化
    scene.screenSpaceCameraController.zoomEventTypes = [
      Cesium.CameraEventType.WHEEL
    ]
    // 设置鼠标右键拖动地图, 允许用户在3D和2.5D模式下倾斜，或者在2D模式下旋转的输入
    scene.screenSpaceCameraController.tiltEventTypes = [
      Cesium.CameraEventType.RIGHT_DRAG
    ]

    // 倾斜视图 鼠标左键旋转
    // viewer.scene.screenSpaceCameraController.tiltEventTypes = [
    //   Cesium.CameraEventType.LEFT_DRAG,
    // ];
    // // 平移 添加鼠标右键  鼠标右键平移
    // viewer.scene.screenSpaceCameraController.rotateEventTypes = [
    //   Cesium.CameraEventType.RIGHT_DRAG,
    // ];

    scene.screenSpaceCameraController.minimumZoomDistance = 0.8;

    setTimeout(() => {
      this.load3D();
    }, 500);

    viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString('rgba(49, 108, 140, 0.8)') //设置地球颜色
    viewer.scene.skyAtmosphere.show = false // 隐藏大气，不隐藏的话周围会有一圈光晕
    viewer._cesiumWidget._creditContainer.style.display = 'none' // 去除logo
    viewer.imageryLayers.removeAll(true) // 移除所有图层并销毁
    // 添加矢量底图与矢量标注图层
    this.addMapStyle("vec");
    // this.addMapStyle("cva");
    // this.addMapStyle("img");
    // this.addMapStyle("cia");
    // 开场动画，旋转到目标位置
    // this.flyToPosition({ lon: 120.1715, lat: 30.2739, height: 150000 }, 3)
    setTimeout(() => {
      this.effectFun();
    }, 500)
  }

  effectFun = () => {
    modifyMap(
      viewer,
      {
        //反色?
        invertColor: true, //反色
        // filterRGB: [10, 49, 85], //过滤器rgb
        filterRGB: [22, 54, 62], //过滤器rgb
        brightness: 0.55, //亮度，值0=1，小于1会减少亮度，大于1会增加亮度
        contrast: 2.58, //对比度，值0=1，小于1会减少对比度、亮度，大于1会增加对比度、亮度
        gamma: 0.1, //值0=1，小于1会增加对比度，大于1会减少对比度
        hue: 0, //颜色，值能为0，可以为正负数，接近0为原始颜色，改变饱和度，轻微改变色相
        saturation: 0.1 //饱和度+色相，值不能为0，可以为正负数，接近0为原始颜色，值距离0越远，饱和度越高，并改变色相
      },
      0,
      false
    )
  }



  /**
   * @加载3D
   * */
  load3D = async () => {
    /* 加载建筑模型 */
    try {
      let url = import.meta.env.VITE_BASE_PUBLICPATH + "/3dTiles/architecture/hangzhou/tileset.json";
      const tileset = await Cesium.Cesium3DTileset.fromUrl(url);
      viewer.scene.primitives.add(tileset);
      titlesObj = tileset;
      /* 设置颜色 */
      tileset.style = new Cesium.Cesium3DTileStyle({
        color: {
          conditions: [
            ["true", "color('rgb(0, 135, 156)',1)"]
          ]
        },
      });
      var customShader = new Cesium.CustomShader({
        lightingModel: Cesium.LightingModel.UNLIT,
        fragmentShaderText: `
                       void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
                           float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
                           float _heightRange = 60.0; // 高亮的范围(_baseHeight ~ _baseHeight + _      heightRange) 默认是 0-60米
                           float _glowRange = 300.0; // 光环的移动范围(高度)
                           float vtxf_height = fsInput.attributes.positionMC.z-_baseHeight;
                           float vtxf_a11 = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
                           float vtxf_a12 = vtxf_height / _heightRange + sin(vtxf_a11) * 0.1;
                           material.diffuse*= vec3(vtxf_a12, vtxf_a12, vtxf_a12);
                           float vtxf_a13 = fract(czm_frameNumber / 360.0);
                           float vtxf_h = clamp(vtxf_height / _glowRange, 0.0, 1.0);
                           vtxf_a13 = abs(vtxf_a13 - 0.5) * 2.0;
                           float vtxf_diff = step(0.005, abs(vtxf_h - vtxf_a13));
                           material.diffuse += material.diffuse * (1.0 - vtxf_diff);
                       }
                       `,
      });
      tileset.customShader = customShader;
      modelThree.bulid.push(tileset);
    } catch (error) {
      console.error(`Error creating tileset: ${error}`);
    }

    /* 加载植株模型 */
    try {
      let url = import.meta.env.VITE_BASE_PUBLICPATH + '/3dTiles/architecture/grass/tileset.json'
      const tileset = await Cesium.Cesium3DTileset.fromUrl(url)
      viewer.scene.primitives.add(tileset)
      /* 设置颜色 */
      tileset.style = new Cesium.Cesium3DTileStyle({
        color: {
          conditions: [['true', "color('#1b703f',0.7)"]]
        }
      })
      modelThree.bulid.push(tileset)
    } catch (error) {
      console.error(`Error creating tileset: ${error}`)
    }

    /* 加载水系模型 */
    try {
      let url = import.meta.env.VITE_BASE_PUBLICPATH + '/3dTiles/architecture/water/tileset.json'
      const tileset = await Cesium.Cesium3DTileset.fromUrl(url)
      viewer.scene.primitives.add(tileset)
      /* 设置颜色 */
      tileset.style = new Cesium.Cesium3DTileStyle({
        color: {
          conditions: [['true', "color('#00aeff',0.7)"]]
        }
      })
      modelThree.bulid.push(tileset)
    } catch (error) {
      console.error(`Error creating tileset: ${error}`)
    }


    /* 加载道路流光 */
    // let roadUrl = "/3dTiles/way/province_government_way.geojson";
    // Cesium.GeoJsonDataSource.load(roadUrl, {
    //   // stroke: Cesium.Color.fromCssColorString("rgba(86, 217, 193, 0.8)"),
    //   stroke: Cesium.Color.fromCssColorString("rgba(211, 200, 113, 0.4)"),
    //   strokeWidth: 3,
    //   clampToGround: true,
    // }).then(function (dataSource) {
    //   viewer.dataSources.add(dataSource);
    //   dataRoad = dataSource;
    //   const entities = dataSource.entities.values;
    //   modelThree.road.push(dataSource);
    //
    //   /* 道路流光 */
    //   for (let i = 0; i < entities.length; i++) {
    //     let entity = entities[i];
    //     entity.polyline.width = 3;
    //     entity.polyline.material = new Spriteline1MaterialProperty(
    //       2000,
    //       "/img/spriteline5.png"
    //     );
    //   }
    // });
  };

  /**
   * @隐藏白膜
   * */
  detele3dTitlesObj = () => {
    titlesObj.show = false;
    // modifyMap(
    //   viewer,
    //   {
    //     invertColor: true, //反色
    //     filterRGB: [10, 49, 85], //过滤器rgb
    //     brightness: 0.55, //亮度，值0=1，小于1会减少亮度，大于1会增加亮度
    //     contrast: 2.58, //对比度，值0=1，小于1会减少对比度、亮度，大于1会增加对比度、亮度
    //     gamma: 0.1, //值0=1，小于1会增加对比度，大于1会减少对比度
    //     hue: 0, //颜色，值能为0，可以为正负数，接近0为原始颜色，改变饱和度，轻微改变色相
    //     saturation: 0.1 //饱和度+色相，值不能为0，可以为正负数，接近0为原始颜色，值距离0越远，饱和度越高，并改变色相
    //
    //   },
    //   0,
    //   false
    // )
  }

  /**
   * @显示白膜
   * */
  detele3dTitlesObjShow = () => {
    titlesObj.show = true;
    this.effectFun()
  }

  // 隐藏路网
  delete3D = () => {
    // dataRoad.show = false;
  }

  // 显示路网
  dataRoadShow = () => {
    // dataRoad.show = true;
  }

  /**
   * @返回初始视角
   * */
  backToStart = () => {
    /* 设置相机位置 */
    viewer.camera.flyTo({
      destination: {
        x: -2789575.5099842506,
        y: 4801085.598874651,
        z: 3170177.394385061
      },
      duration: 2,
      orientation: {
        // 初始视角
        heading: 6.238757102061567,
        pitch: -0.5230891552682251,
        roll: 0.000030715561083027865,
      }
    });
  }

  /**
   * @为cesimu添加天地图的底图
   * @param layer  底图样式
   * vec：矢量底图、cva：矢量标注、img：影像底图、cia：影像标注
   * ter：地形晕渲、cta：地形标注、eva：矢量英文标注、eia：影像英文标注
   */
  addMapStyle(layer) {
    // 添加天地图底图
    const tMapImagery = new Cesium.WebMapTileServiceImageryProvider({
      url: `http://t0.tianditu.gov.cn/${layer}_w/wmts?tk=a6286340f24554c6ab89391bd9abe42f`,
      layer,
      style: "default",
      tileMatrixSetID: "w",
      format: "tiles",
      maximumLevel: 18,
    });
    viewer.imageryLayers.addImageryProvider(tMapImagery);

    if (layer == "img") {
      //   setTimeout(() => {
      //     modifyMap(
      //       viewer,
      //       {
      //         invertColor: true, //反色
      //         filterRGB: [10, 49, 85], //过滤器rgb
      //         brightness: 0.55, //亮度，值0=1，小于1会减少亮度，大于1会增加亮度
      //         contrast: 2.58, //对比度，值0=1，小于1会减少对比度、亮度，大于1会增加对比度、亮度
      //         gamma: 0.1, //值0=1，小于1会增加对比度，大于1会减少对比度
      //         hue: 0, //颜色，值能为0，可以为正负数，接近0为原始颜色，改变饱和度，轻微改变色相
      //         saturation: 0.1 //饱和度+色相，值不能为0，可以为正负数，接近0为原始颜色，值距离0越远，饱和度越高，并改变色相
      //
      //       },
      //       0,
      //       false
      //     )
      //   })
    }
  }

  /**
   * @移除cesimu底图
   */
  removeMapStyle(layer) {
    const index = viewer.imageryLayers._layers.findIndex(item => item._imageryProvider._layer === layer)
    viewer.imageryLayers.remove(viewer.imageryLayers.get(index))
  }

  /**
   * @description : 初始场景动画，飞到目标点
   * @param {*} position ：目标点位置
   * @param {*} duration ：持续时间
   * @return {*}
   */
  flyToPosition(position, duration) {
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(position.lon, position.lat, position.height),
      duration: duration,
    });
  }

  /**
   * @description : 添加图标
   */
  drawMarker(cameraArras) {
    console.log("DIANlllllllllllll", cameraArras)
    if (cameraArras.length < 1) return;
    for (var i = 0; i < cameraArras.length; i++) {
      this.removeView([cameraArras[i]]);
      // let id = cameraArras[i].EntityType === 'aircraft' && !cameraArras[i].droneSerialId
      viewer.entities.add({
        id: cameraArras[i].id,
        position: Cesium.Cartesian3.fromDegrees(cameraArras[i].longitude, cameraArras[i].latitude, cameraArras[i].height || 200.0),
        billboard: {
          //这里需要改成您本地的路径的图片信息。
          image: cameraArras[i].icon,
          height: 47,
          width: 42,
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        label: cameraArras[i].EntityType === "plane" ? {
          // 文本。支持显式换行符“ \ n”
          text: `${cameraArras[i].droneSerialId}`,
          // 字体样式，以CSS语法指定字体
          font: '12px Source Han Sans CN',
          // 字体颜色
          fillColor: Cesium.Color.WHITE,
          // 背景颜色
          backgroundColor: Cesium.Color.fromCssColorString('#091c24').withAlpha(0.6),    //背景颜色
          // 是否显示背景颜色
          showBackground: true,
          style: Cesium.LabelStyle.FILL,        //label样式
          // 字体边框
          outline: true,
          // 字体边框颜色
          outlineColor: Cesium.Color.fromCssColorString('#00f3f6').withAlpha(0.6),
          // 字体边框尺寸
          outlineWidth: 1,
          // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
          scale: 1.0,
          // 相对于坐标的水平位置
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          // 相对于坐标的水平位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
          pixelOffset: new Cesium.Cartesian2(-30, -30),
        } : "",
        EntityType: cameraArras[i].EntityType,
        cursorHand: true,
      });
    }
  }

  /**
   * @description : 监听
   */
  setDrawHandler() {
    //注册场景点击事件
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (e) {
      var pick = viewer.scene.pick(e.position);

      if (pick && pick.id) {
        let id = pick.id._airspaceApplyId || pick.id._id;
        let entity = viewer.entities.getById(id)
        // console.log("entityentityentity", id);
        // console.log("entityentityentity", entity);
        if (pick && pick.id._EntityType === "Wind") {
          this.windDraw();
          // viewer.entities.add({
          //   name: 'Rotating rectangle with rotating texture coordinate',
          //   rectangle: {
          //     coordinates: Cesium.Rectangle.fromDegrees( 119.90262903783662 , 30.057825292736652, 120.42355638162552 , 30.4763484435697), // 给经纬度确定绘制边界  西 南 东 北
          //     material: new Cesium.ImageMaterialProperty({
          //       //添加回调
          //       // image: new Cesium.CallbackProperty(function () {
          //       //   var canvas = document.getElementById("canvas-" + curCanvas);
          //       //   var context = canvas.getContext('2d');
          //       //   //省略
          //       //   curCanvas = curCanvas === 'a' ? 'b' : 'a';
          //       //   return canvas;
          //       // }, false),
          //       image: "/img/windTrends.png",
          //       transparent: 0.4
          //     })
          //   }
          // });
        } else {
          //点击物体的属性都存在pick.id内部
          entityPosition = e.position;
          viewer.entities.values.map((item) => {
            // console.log(pick.id);
            if (pick.id._id && (item._id == pick.id._id)) {
              var ray = viewer.camera.getPickRay(entityPosition);
              var cartesian = viewer.scene.globe.pick(ray, viewer.scene);
              var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
              var lng = Cesium.Math.toDegrees(cartographic.longitude);//经度值
              var lat = Cesium.Math.toDegrees(cartographic.latitude);//纬度值
              if (pick.id._EntityType === "airspace") {
                viewer.camera.flyTo({
                  destination: Cesium.Cartesian3.fromDegrees(lng, lat, 50000),
                  duration: 1,
                });
              } else if (
                pick.id._EntityType === "device" ||
                pick.id._EntityType === "airline" ||
                pick.id._EntityType === "company" ||
                pick.id._EntityType === "airport"
              ) {
                viewer.flyTo(entity);
              }
              cockpitFun(id, entityPosition, pick.id.EntityType)
            }
          })
        }
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }

  windDraw() {
    let canvas = document.createElement("canvas");
    let url = import.meta.env.VITE_BASE_PUBLICPATH + "/img/windTrends.png";
    let gifImageLayer;
    let rectangle = Cesium.Rectangle.fromDegrees(...[119.90262903783662, 30.057825292736652, 120.42355638162552, 30.4763484435697]);

    function onDrawFrame(ctx, frame) {
      ctx.canvas.width = frame.width;
      ctx.canvas.height = frame.height;

      ctx.drawImage(frame.buffer, 0, 0);

      const provider = new Cesium.SingleTileImageryProvider({
        url: canvas.toDataURL(),
        rectangle
      });
      gifImageLayer = viewer.imageryLayers.addImageryProvider(provider);
    }

    gifler(url).frames(canvas, onDrawFrame);

  }

  /**
   * @description : 添加虚线
   */
  drawLine(data) {
    let line = new Cesium.Entity({
      name: 'line',
      show: true,
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(data.position),
        width: 6,
        material: new Cesium.PolylineDashMaterialProperty({
          color: data.color ? Cesium.Color.fromCssColorString(data.color).withAlpha(1) : Cesium.Color.YELLOW.withAlpha(1),
          dashLength: 40, //短划线长度
        }),


        // followSurface: true,
        // material: new Cesium.PolylineGlowMaterialProperty({
        //   color: Cesium.Color.GREEN,
        //   // dashLength: 50, //短划线长度
        //   glowPower: 0.7
        // })
      },
      zIndex: 200,
      EntityType: data.EntityType,
      id: data.airspaceApplyId,
      cursorHand: true
    });

    let point = null
    if (data.EntityType === 'airline') {
      point = new Cesium.Entity({
        name: "point",
        show: true,
        position: Cesium.Cartesian3.fromDegrees(data.position[0], data.position[1], 5000),
        // 点
        point: {
          color: Cesium.Color.RED.withAlpha(0.8), // 点位颜色
          pixelSize: 15, // 像素点大小
        },
        // 文字
        label: {
          // 文本。支持显式换行符“ \ n”
          text: `${data.applyName}的${data.taskName}航线`,
          // 字体样式，以CSS语法指定字体
          font: '14pt Source Han Sans CN',
          // 字体颜色
          fillColor: Cesium.Color.WHITE,
          // 背景颜色
          backgroundColor: Cesium.Color.fromCssColorString('rgb(9, 27, 35)'),
          // 是否显示背景颜色
          showBackground: true,
          // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
          scale: 1.0,
          // 相对于坐标的水平位置
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          // 相对于坐标的水平位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
          pixelOffset: new Cesium.Cartesian2(0, 15),
          // 显示在距相机的距离处的属性，多少区间内是可以显示的
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 30000),
        }

      })
      viewer.entities.add(point);
    }

    viewer.entities.add(line);
    viewer.zoomTo(viewer.entities);

    return { line, point }
  }

  /**
    * @description : 添加方形管道线
  */
  drawLine1(data) {
    console.log("drawLine1", data);

    function starPositions(arms, rOuter, rInner) {
      const angle = Math.PI / arms;
      const pos = [];
      for (let i = 0; i < 2 * arms; i++) {
        const r = i % 2 === 0 ? rOuter : rInner;
        const p = new Cesium.Cartesian2(
          Math.cos(i * angle) * r,
          Math.sin(i * angle) * r
        );
        pos.push(p);
      }
      return pos;
    }

    let line = new Cesium.Entity({
      name: 'line',
      show: true,
      polylineVolume: {
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(data.position),
        shape: starPositions(2, 20.0, 20.0),
        material: data.color ? Cesium.Color.fromCssColorString(data.color).withAlpha(1) : (data.aircraftType === 4 ? Cesium.Color.PINK.withAlpha(0.9) : Cesium.Color.PURPLE.withAlpha(0.9)),
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      },
      zIndex: 200,
      EntityType: data.EntityType,
      id: data.airspaceApplyId,
      cursorHand: true
    });



    let startPoint = null
    let endPoint = null
    let standbyPoint = null;
    let standbyLine = null;
    if (data.EntityType === 'airline') {
      startPoint = new Cesium.Entity({
        name: "point",
        show: true,
        position: Cesium.Cartesian3.fromDegrees(...data.takeoffPoint),
        // 图标
        billboard: {
          image: data.iconS,
          height: 47,
          width: 42,
          pixelOffset: new Cesium.Cartesian2(0, -20),
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        airspaceApplyId: data.airspaceApplyId,
        EntityType: data.EntityType,
        cursorHand: true
      })
      endPoint = new Cesium.Entity({
        name: "point",
        show: true,
        position: Cesium.Cartesian3.fromDegrees(...data.landingPoint),
        billboard: {
          //这里需要改成您本地的路径的图片信息。
          image: data.iconE,
          height: 47,
          width: 42,
          // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
          pixelOffset: new Cesium.Cartesian2(0, -20),
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        airspaceApplyId: data.airspaceApplyId,
        EntityType: data.EntityType,
        cursorHand: true
      })
      viewer.entities.add(startPoint);
      viewer.entities.add(endPoint);
    }
    if (data.standbyPosition) {
      standbyLine = new Cesium.Entity({
        name: 'line',
        show: true,
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArrayHeights(data.standbyPosition),
          width: 6,
          material: new Cesium.PolylineDashMaterialProperty({
            color: Cesium.Color.fromCssColorString(data.color).withAlpha(1),
            dashLength: 20, //短划线长度
          }),
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        // id: data.airspaceApplyId + "standbyLine",
        airspaceApplyId: data.airspaceApplyId,
        EntityType: data.EntityType,
        cursorHand: true
      })
      standbyPoint = new Cesium.Entity({
        name: "point",
        show: true,
        position: Cesium.Cartesian3.fromDegrees(...data.standbyPoint),
        // 图标
        billboard: {
          image: data.iconB,
          height: 47,
          width: 42,
          pixelOffset: new Cesium.Cartesian2(0, -20),
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        // id: data.airspaceApplyId + "standbyPoint",
        airspaceApplyId: data.airspaceApplyId,
        EntityType: data.EntityType,
        cursorHand: true
      })
      viewer.entities.add(standbyPoint);
      viewer.entities.add(standbyLine);
    }


    viewer.entities.add(line);
    // viewer.zoomTo(viewer.entities);

    return { line, endPoint, startPoint, standbyPoint, standbyLine }
  }

  /**
    * @description : 添加圆形管道线
  */
  drawLine2(data) {
    // console.log("drawLine2", data);
    function computeCircle(radius) {
      const positions = [];
      for (let i = 0; i < 360; i++) {
        const radians = Cesium.Math.toRadians(i);
        positions.push(
          new Cesium.Cartesian2(
            radius * Math.cos(radians),
            radius * Math.sin(radians)
          )
        );
      }
      return positions;
    }

    // 飞行轨迹
    let line = null;
    let planePoint = null;
    if (data.EntityType === "Planetrack") {
      line = new Cesium.Entity({
        name: 'line',
        show: true,
        polylineVolume: {
          positions: Cesium.Cartesian3.fromDegreesArrayHeights(data.position),
          shape: computeCircle(5.0),
          material: data.color ? Cesium.Color.fromCssColorString(data.color).withAlpha(1) : (data.aircraftType === 4 ? Cesium.Color.PINK.withAlpha(0.9) : Cesium.Color.PURPLE.withAlpha(0.9)),
        },
        zIndex: 200,
        EntityType: data.EntityType,
        id: data.airspaceApplyId,
        cursorHand: true
      });
      planePoint = new Cesium.Entity({
        name: "point",
        show: true,
        position: Cesium.Cartesian3.fromDegrees(...data.curPosition),
        billboard: {
          //这里需要改成您本地的路径的图片信息。
          image: data.icon,
          height: 47,
          width: 42,
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        }
      })
      viewer.entities.add(line);
      viewer.entities.add(planePoint);
      viewer.flyTo(line)
    }

    // 飞手
    let driverPoint = null;
    // 飞手到航线起点连线
    let flyHandToAircraft = null;
    if (data.driverIcon) {
      driverPoint = new Cesium.Entity({
        name: "point",
        show: true,
        position: Cesium.Cartesian3.fromDegrees(...data.dirverPosition),
        billboard: {
          //这里需要改成您本地的路径的图片信息。
          image: data.driverIcon,
          height: 47,
          width: 42,
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        }
      })
      flyHandToAircraft = new Cesium.Entity({
        name: 'line',
        show: true,
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArrayHeights(data.flyHandToAircraft),
          width: 1,
          material: new Cesium.PolylineDashMaterialProperty({
            color: Cesium.Color.fromCssColorString(data.flyHandLineColor).withAlpha(1),
            dashLength: 20, //短划线长度
          }),
        },
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      });
      viewer.entities.add(driverPoint);
      viewer.entities.add(flyHandToAircraft);
      viewer.flyTo(flyHandToAircraft)
    }
    let entitydd = null;
    if (data.isTrack) {
      let arr = []
      // let arrhist = []
      let property = new Cesium.SampledPositionProperty()
      let starttime = new Date()
      let stoptime
      let timestamp = starttime.getTime()
      let linePositions = this.Deduplication(data.trackLine);
      linePositions.forEach((item, index) => {
        arr.push(Number(item[0]), Number(item[1]), Number(item[2]));
        let time = new Date(timestamp + index * 5000)
        stoptime = time
        let position = Cesium.Cartesian3.fromDegrees(
          Number(item[0]), Number(item[1]), Number(item[2])
        )
        property.addSample(Cesium.JulianDate.fromDate(time), position)
      })
      property.setInterpolationOptions({
        interpolationDegree: 0.0001,
        interpolationAlgorithm: Cesium.LagrangePolynomialApproximation,
      })
      entitydd = new Cesium.Entity({
        availability: new Cesium.TimeIntervalCollection([
          new Cesium.TimeInterval({
            start: Cesium.JulianDate.fromDate(starttime),
            stop: Cesium.JulianDate.fromDate(new Date(stoptime)),
          }),
        ]),
        // 点集
        position: property,
        // 朝向
        orientation: new Cesium.VelocityOrientationProperty(property),
        // 模型
        // model: {
        //   uri: '/3dTiles/model/drone.glb', // 飞机模型
        //   scale: 0.8, // 模型轮廓大小
        //   minimumPixelSize: 70,
        //   maximumScale: 70,
        // },
        billboard: {
          image: data.droneIcon, // 图像地址，URI或Canvas的属性
          width: 40, // 宽度（以像素为单位）
          height: 40, // 高度（以像素为单位）
          verticalOrigin: Cesium.VerticalOrigin.CENTER, // 相对于坐标的垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 相对于坐标的水平位置
          show: true, // 是否显示
          disableDepthTestDistance: Number.POSITIVE_INFINITY
        },
        // 飞行过的路径
        path: {
          leadTime: 0,
          resolution: 1,
          material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.1,
            color: Cesium.Color.fromCssColorString(data.color).withAlpha(1),
          }),
          width: 15,
        },
        // disableDepthTestDistance: Number.POSITIVE_INFINITY,
        id: data.id + "track",
        viewFrom: new Cesium.Cartesian3(500, 500, 100), // 偏移量--设置视角高度
      })
      // viewer.trackedEntity = entitydd   // 视角跟随
      viewer.clock.currentTime = Cesium.JulianDate.fromDate(starttime) //修改时间轴的当前时间
      viewer.clock.stopTime = Cesium.JulianDate.fromDate(new Date(stoptime))
      viewer.clock.clockRange = Cesium.ClockRange.CLAMPED
      viewer.clock.shouldAnimate = true //开始播放
      viewer.entities.add(entitydd);
    }


    // return { line, driverPoint, dronePoint, flyHandToAircraft, entitydd }
    return { line, planePoint, driverPoint, flyHandToAircraft, entitydd }
  }


  /**
    * @description : 航线点位去重（相邻点位）
  */
  Deduplication(linePoints) {
    const arr = [];
    let len = linePoints.length;
    for (let i = 0; i < len; i++) {
      const curPoint = linePoints[i];
      if (i === len - 1) {
        arr.push(curPoint);
        break;
      }
      const nextPoint = linePoints[i + 1];
      let isDifferent = curPoint.some((item, index) => {
        return item !== nextPoint[index]
      })
      if (isDifferent) {
        arr.push(curPoint);
      }
    }
    return arr;
  }

  /**
    * @description : 添加多边形
  */
  drawPolygon(item) {
    console.log(item.EntityType)
    let positions = Cesium.Cartesian3.fromDegreesArray(item.pointLocation.match(/-?\d+\.\d+/g).map(Number))
    let polygon = new Cesium.Entity({
      polygon: {
        // 获取指定属性（positions）
        hierarchy: new Cesium.PolygonHierarchy(positions),
        // extrudedHeight: item.lowHeight,
        height: item.lowHeight,
        extrudedHeight: item.topHeight,
        // 边框
        outline: true,
        // 边框颜色
        outlineColor: Cesium.Color.fromCssColorString(item.lineColor).withAlpha(1),
        // 边框尺寸
        outlineWidth: 20,
        // 填充的颜色，withAlpha透明度
        material: Cesium.Color.fromCssColorString(item.fullColor).withAlpha(0.3),
        // 是否被提供的材质填充
        fill: true,
        // 是否显示
        show: true,
        // 顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。
        zIndex: 0
      },
      EntityType: item.EntityType,
      id: item.airspaceId,
      cursorHand: true
    });

    // console.log("IIIIIIIIIIIII", polygon)
    viewer.entities.add(polygon);

    return polygon;
  }

  /**
    * @description : 添加圆形
  */
  drawCircle(item) {
    console.log(item)
    let positions = item.pointLocation.split(",").map(Number)
    let circle = new Cesium.Entity({
      position: Cesium.Cartesian3.fromDegrees(...positions),

      ellipse: {
        semiMinorAxis: item.radius,
        semiMajorAxis: item.radius,
        height: item.lowHeight,
        extrudedHeight: item.topHeight,
        outline: false,
        // outlineWidth: 20,
        //   outlineColor: Cesium.Color.fromCssColorString(item.lineColor).withAlpha(1),
        material: Cesium.Color.fromCssColorString(item.fullColor).withAlpha(0.3),
      },
      EntityType: item.EntityType,
      id: item.airspaceId,
      cursorHand: true
    });

    viewer.entities.add(circle);
    return circle;
  }

  /**
    * @description : 添加扫描圈
  */
  drawScanCircle(position) {
    let scanCircle = new Cesium.Entity({
      position: Cesium.Cartesian3.fromDegrees(...position),
      name: '扫描圆',
      ellipse: {
        semiMinorAxis: 6000.0,
        semiMajorAxis: 6000.0,
        material: new CircleRippleMaterialProperty({
          color: Cesium.Color.fromCssColorString("#f00").withAlpha(0.6),
          speed: 12.0,
          count: 4,
          gradient: 0.2
        })
      },
    })
    viewer.entities.add(scanCircle);
    return scanCircle;
  }

  /**
   * 笛卡尔坐标转换经纬度坐标
   * @param {*} car3_ps
   * @returns
   */
  getLngLatByCartesian3(car3_ps, type) {
    let result = null;
    if (car3_ps instanceof Cesium.Cartesian3) {
      let _cartographic = Cesium.Cartographic.fromCartesian(car3_ps);
      let _lat = Cesium.Math.toDegrees(_cartographic.latitude);
      let _lng = Cesium.Math.toDegrees(_cartographic.longitude);
      let _alt = _cartographic.height;
      if (type == 'polyline') {
        result = { longitude: _lng, latitude: _lat, elevation: _alt }
      } else {
        result = { lng: _lng, lat: _lat, alt: _alt }
      }
      return result;
    } else if (car3_ps instanceof Array) {
      let res = [];
      for (let i = 0; i < car3_ps.length; i++) {
        let _cartographic = Cesium.Cartographic.fromCartesian(car3_ps[i]);
        let _lat = Cesium.Math.toDegrees(_cartographic.latitude);
        let _lng = Cesium.Math.toDegrees(_cartographic.longitude);
        let _alt = _cartographic.height;
        if (type == 'polyline') {
          res.push({ longitude: _lng, latitude: _lat, elevation: _alt })
        } else {
          res.push({ lng: _lng, lat: _lat, alt: _alt })
        }
      }
      return res;
    }
  }

  /**
     * @description : 移除地图标记
  */
  removeView(list) {
    if (list.length < 1) return;
    list.forEach(item => {
      viewer.entities.remove(item)
    })
  }

  /**
     * @description : 隐藏地图标记
  */
  hideView(list) {
    if (list.length > 0) {
      list.forEach(item => {
        item.show = false
      })
    }
  }

  /**
     * @description : 显示地图标记
  */
  showView(list) {
    if (list.length > 0) {
      list.forEach(item => {
        item.show = true
      })
    }
  }

  /**
   * @description : 云图
   */
  nephogram() {
    const entities = viewer.entities;

    const image = 'https://openlayers.vip/examples/resources/earth_cloud.png';

    const color = new Cesium.Color(1.0, 1.0, 1.0, 1);

    const time = 20;

    const imageMaterial = new Cesium.ImageMaterialProperty({
      image: image
    });

    // 创建矩形实体
    nephogramEntity = entities.add({
      rectangle: {
        coordinates: Cesium.Rectangle.fromDegrees(-180.0, -90.0, 180.0, 90.0),
        material: imageMaterial,
      },
    });

    viewer.zoomTo(viewer.entities);
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(120.30279176049339, 30.23518121326055, 10000000),
      // duration: duration,
    });

    // Sandcastle.addToolbarButton("开启动态云层", function () {
    //   alert('动态云层！');
    //   entity.rectangle.height = 0;
    //   entity.rectangle.extrudedHeight = 100000;
    //   entity.rectangle.material = new CloudEffectMaterial();
    // });
  }

  /**
   * @description : 关闭云图
   */
  closeNephogram() {
    viewer.entities.remove(nephogramEntity)

    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(120.10818975983456, 30.168607527215354, 10000),
      orientation: {
        heading: 0.21620258115286184,
        pitch: -0.6162261574821861,
        roll: 0.0001285856161814536,
      }
    });
    // const center = Cesium.Cartesian3.fromDegrees(120.30279176049339, 30.23518121326055);
    // const heading = Cesium.Math.toRadians(0.21620258115286184);
    // const pitch = Cesium.Math.toRadians(-0.6162261574821861);
    // const range = 15000.0;
    // viewer.camera.flyToBoundingSphere(
    //     new Cesium.BoundingSphere(center, 5000),
    //     {
    //       offset: new Cesium.HeadingPitchRange(heading, pitch, range),
    //       duration: 2,
    //     },
    // );
  }

  /**
   * @description : 热力图
   */
  heatMapChange(value) {
    if (heatMap) {
      heatMap.show(true);
    } else {
      let bounds = {  // 热力区域范围，一个矩形区域
        east: 120.67887078506858,
        west: 119.5976263762144,
        south: 29.968787027382774,
        north: 30.523175162149798
      };

      // init heatmap
      heatMap = CesiumHeatmap.create(
        viewer, // your cesium viewer
        bounds, // bounds for heatmap layer
        {
          // heatmap.js options go here
          "gradient": {
            "0.05": "rgb(0, 0, 255)",
            "0.45": "rgb(38, 131, 102)",
            "0.65": "rgb(255, 255, 0)",
            "1.00": "rgb(255, 0, 0)"
          },
          radius: 190, // 热点半径
          blur: 0.75, //模糊尺寸
          maxOpacity: 0.85, // 最大不透明度
          minOpacity: 0.36,  //最小不透明度
        }
      );

      // random example data
      let data = [
        { "x": 120.169329, "y": 30.242312, "value": value[0] }, // 上城区 284869
        // { "x": 120.17, "y": 30.28, "value": 13 }, // 下城区
        // { "x": 120.2, "y": 30.27, "value": 22 }, // 江干区
        { "x": 120.141391, "y": 30.319424, "value": value[1] }, // 拱墅区  284872
        { "x": 120.13006, "y": 30.259543, "value": value[2] }, // 西湖区  284873
        { "x": 120.211816, "y": 30.20856, "value": value[3] }, // 滨江区  284874
        { "x": 120.2597929, "y": 30.15987182, "value": value[4] }, // 萧山区 1186
        { "x": 120.3034996, "y": 30.42032592, "value": value[5] }, // 余杭区 1187
        { "x": 119.9460172, "y": 30.05939327, "value": value[6] }, // 富阳市 1189
        { "x": 119.7153043, "y": 30.22959808, "value": value[7] }, // 临安市 1190
        { "x": 120.299094, "y": 30.419183, "value": value[8] }, // 临平区 287062
        { "x": 120.497834, "y": 30.299469, "value": value[9] }]; // 钱塘区 287063
      let valueMin = 0;  // 最小热力值
      let valueMax = 100;  // 最大热力值

      // add data to heatmap
      heatMap.setWGS84Data(valueMin, valueMax, data);

      viewer.camera.setView({
        destination: Cesium.Rectangle.fromDegrees(bounds.west, bounds.south, bounds.east, bounds.north)
      });
    }
  }

  /**
   * @description : 关闭热力图
   */
  closeHeatMapChange() {
    heatMap.show(false);
  }

  /**
   * @description : 轨迹动画
   */
  trajectoryAnimation() {
    historycode_line.push(history_line)
    let modelUrl = import.meta.env.VITE_BASE_PUBLICPATH + '/3dTiles/model/drone.gltf'
    // 线动画
    let entitydd = viewer.entities.add({
      availability: new Cesium.TimeIntervalCollection([
        new Cesium.TimeInterval({
          start: Cesium.JulianDate.fromDate(starttime),
          stop: Cesium.JulianDate.fromDate(new Date(stoptime)),
        }),
      ]),
      // 点集
      position: property,
      // 朝向
      orientation: new Cesium.VelocityOrientationProperty(property),
      // 模型
      model: {
        uri: modelUrl, // 飞机模型
        scale: 0.8, // 模型轮廓大小
        minimumPixelSize: 70,
        maximumScale: 70,
      },
      // 路径
      path: {
        leadTime: 0,
        resolution: 1,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.GREEN,
        }),
        width: 6,
      },
      viewFrom: new Cesium.Cartesian3(500, 500, 100), // 偏移量--设置视角高度
    })
    // 视角轨迹路径
    perspectiveEntity = viewer.entities.add({
      availability: new Cesium.TimeIntervalCollection([
        new Cesium.TimeInterval({
          start: Cesium.JulianDate.fromDate(starttime),
          stop: Cesium.JulianDate.fromDate(new Date(stoptime)),
        }),
      ]),
      // 点集
      position: perspectiveProperty,
      // 朝向
      orientation: new Cesium.VelocityOrientationProperty(perspectiveProperty),

      viewFrom: new Cesium.Cartesian3(500, 500, 100), // 偏移量--设置视角高度
    })
    // hisstrdata_markers.push(entitydd)
    // hisstrdata_markers.push(perspectiveEntity)
    let timeOut = stoptime - starttime
    viewer.trackedEntity = entitydd
    viewer.clock.currentTime = Cesium.JulianDate.fromDate(starttime) //修改时间轴的当前时间
    viewer.clock.stopTime = Cesium.JulianDate.fromDate(new Date(stoptime))
    viewer.clock.clockRange = Cesium.ClockRange.CLAMPED
    viewer.clock.shouldAnimate = true //开始播放
    // 视角跟随
    viewer.scene.postUpdate.addEventListener(handlePostUpdate)

    arrhist.push(
      dataArr[0].longitude,
      dataArr[0].latitude,
      0,
      dataArr[dataArr.length - 1].longitude,
      dataArr[dataArr.length - 1].latitude,
      0
    )
    let history_doshline = viewer.entities.add({
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArrayHeights([...arrhist]),
        // 宽度
        width: 3,
        material: new Cesium.PolylineDashMaterialProperty({
          // 虚线
          color: Cesium.Color.fromCssColorString('skyblue'),
        }),
        show: true, // 是否显示
        clampToGround: true, // 开启贴地
      },
    })

    historycode_line.push(history_doshline)

  }

  /**
   * @description : 温度
   */
  temparetureDraw(val) {
    this.delete3D();
    let list = val;
    let list2 = []
    for (var i = 0; i < list.length; i++) {
      let point = new Cesium.Entity({
        // fromDegrees（经度，纬度，高度，椭球，结果）从以度为单位的经度和纬度值返回Cartesian3位置
        position: Cesium.Cartesian3.fromDegrees(list[i].lon, list[i].lat, 300),
        billboard: {
          //这里需要改成您本地的路径的图片信息。
          image: list[i].icon,
          height: 30,
          width: 30,
        },
        label: {
          text: list[i].label + " " + list[i].condition + " " + list[i].temp.toString() + "℃",
          font: '14px Source Han Sans CN',    //字体样式
          fillColor: Cesium.Color.WHITE,        //字体颜色
          backgroundColor: Cesium.Color.fromCssColorString('rgb(0, 133, 19)').withAlpha(0.8),    //背景颜色
          showBackground: true,                //是否显示背景颜色
          style: Cesium.LabelStyle.FILL,        //label样式
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,//垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,//水平位置
          pixelOffset: new Cesium.Cartesian2(20, 0)            //偏移
        }
      })
      viewer.entities.add(point);
      list2.push(point)
      /* 设置相机位置 */
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(120.15416321882283, 30.255439142676586, 90000),
        duration: 2,
        orientation: {
          // 初始视角
          heading: 6.0908792936288245,
          pitch: -1.5659380609156122,
          roll: 0,
        },
      });
    }
    return list2
  }

  /**
   * @description : 关闭温度
   */
  closeTemparetureDraw(val) {
    if (val.length === 0) return;
    val.forEach(item => {
      viewer.entities.remove(item)
    })
    /* 设置相机位置 */
    viewer.camera.flyTo({
      destination: {
        x: -2789575.5099842506,
        y: 4801085.598874651,
        z: 3170177.394385061
      },
      duration: 2,
      orientation: {
        // 初始视角
        heading: 6.238757102061567,
        pitch: -0.5230891552682251,
        roll: 0.000030715561083027865,
      }
    });
  }

  /**
   * @description : 降水
   */
  precipitationDraw(val) {
    this.delete3D();
    let list = val;
    let list2 = []
    for (var i = 0; i < list.length; i++) {
      let point = new Cesium.Entity({
        // fromDegrees（经度，纬度，高度，椭球，结果）从以度为单位的经度和纬度值返回Cartesian3位置
        position: Cesium.Cartesian3.fromDegrees(list[i].lon, list[i].lat, 300),
        billboard: {
          //这里需要改成您本地的路径的图片信息。
          image: list[i].icon,
          height: 30,
          width: 30,
        },
        label: {
          text: list[i].label + " " + list[i].condition,
          font: '14px Source Han Sans CN',    //字体样式
          fillColor: Cesium.Color.WHITE,        //字体颜色
          backgroundColor: Cesium.Color.fromCssColorString('rgb(0, 255, 102)').withAlpha(0.8),    //背景颜色
          showBackground: true,                //是否显示背景颜色
          style: Cesium.LabelStyle.FILL,        //label样式
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,//垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,//水平位置
          pixelOffset: new Cesium.Cartesian2(20, 0)            //偏移
        }
      })
      viewer.entities.add(point);
      /* 设置相机位置 */
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(120.15416321882283, 30.255439142676586, 90000),
        duration: 2,
        orientation: {
          // 初始视角
          heading: 6.0908792936288245,
          pitch: -1.5659380609156122,
          roll: 0,
        },
      });
      list2.push(point)
    }
    return list2
  }

  /**
   * @description : 关闭降水
   */
  closePrecipitationDraw(val) {
    if (val.length === 0) return;
    val.forEach(item => {
      viewer.entities.remove(item)
    })
    /* 设置相机位置 */
    viewer.camera.flyTo({
      destination: {
        x: -2789575.5099842506,
        y: 4801085.598874651,
        z: 3170177.394385061
      },
      duration: 2,
      orientation: {
        // 初始视角
        heading: 6.238757102061567,
        pitch: -0.5230891552682251,
        roll: 0.000030715561083027865,
      }
    });
  }

  /**
   * @description : 风力
   */
  windPowerDraw(val) {
    this.delete3D();
    let list = val;
    let list2 = []
    for (var i = 0; i < list.length; i++) {
      let point = new Cesium.Entity({
        // fromDegrees（经度，纬度，高度，椭球，结果）从以度为单位的经度和纬度值返回Cartesian3位置
        position: Cesium.Cartesian3.fromDegrees(list[i].lon, list[i].lat, 300),
        billboard: {
          //这里需要改成您本地的路径的图片信息。
          image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/weather/windLevel.png",
          height: 30,
          width: 30,
        },
        label: {
          text: list[i].label + " " + list[i].windSpeed + "km/h" + " " + list[i].windDir + " " + list[i].windLevel + "级",
          font: '14px Source Han Sans CN',    //字体样式
          fillColor: Cesium.Color.WHITE,        //字体颜色
          backgroundColor: Cesium.Color.fromCssColorString('rgb(0, 133, 19)').withAlpha(0.8),    //背景颜色
          showBackground: true,                //是否显示背景颜色
          style: Cesium.LabelStyle.FILL,        //label样式
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,//垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,//水平位置
          pixelOffset: new Cesium.Cartesian2(20, 0)            //偏移
        }
      })
      viewer.entities.add(point);
      /* 设置相机位置 */
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(120.15416321882283, 30.255439142676586, 90000),
        duration: 2,
        orientation: {
          // 初始视角
          heading: 6.0908792936288245,
          pitch: -1.5659380609156122,
          roll: 0,
        },
      });
      list2.push(point)
    }
    return list2
  }

  /**
   * @description : 关闭风力
   */
  closeWindPowerDraw(val) {
    if (val.length === 0) return;
    val.forEach(item => {
      viewer.entities.remove(item)
    })
    /* 设置相机位置 */
    viewer.camera.flyTo({
      destination: {
        x: -2789575.5099842506,
        y: 4801085.598874651,
        z: 3170177.394385061
      },
      duration: 2,
      orientation: {
        // 初始视角
        heading: 6.238757102061567,
        pitch: -0.5230891552682251,
        roll: 0.000030715561083027865,
      }
    });
  }

  /**
   * @description : 风速
   */
  windSpeedDraw(val) {
    this.delete3D();
    let list = val;
    let list2 = []
    for (var i = 0; i < list.length; i++) {
      let point = new Cesium.Entity({
        // fromDegrees（经度，纬度，高度，椭球，结果）从以度为单位的经度和纬度值返回Cartesian3位置
        position: Cesium.Cartesian3.fromDegrees(list[i].lon, list[i].lat, 300),
        // billboard: {
        //   //这里需要改成您本地的路径的图片信息。
        //   image: list[i].icon,
        //   height: 30,
        //   width: 30,
        // },
        label: {
          text: list[i].label + " " + list[i].windSpeed + "千米/时",
          font: '14px Source Han Sans CN',    //字体样式
          fillColor: Cesium.Color.WHITE,        //字体颜色
          backgroundColor: Cesium.Color.fromCssColorString('rgb(0, 255, 102)').withAlpha(0.8),    //背景颜色
          showBackground: true,                //是否显示背景颜色
          style: Cesium.LabelStyle.FILL,        //label样式
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,//垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,//水平位置
          pixelOffset: new Cesium.Cartesian2(20, 0)            //偏移
        }
      })
      viewer.entities.add(point);
      /* 设置相机位置 */
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(120.15416321882283, 30.255439142676586, 90000),
        duration: 2,
        orientation: {
          // 初始视角
          heading: 6.0908792936288245,
          pitch: -1.5659380609156122,
          roll: 0,
        },
      });
      list2.push(point)
    }
    return list2
  }

  /**
   * @description : 关闭风速
   */
  closeWindSpeedDraw(val) {
    if (val.length === 0) return;
    val.forEach(item => {
      viewer.entities.remove(item)
    })
    /* 设置相机位置 */
    viewer.camera.flyTo({
      destination: {
        x: -2789575.5099842506,
        y: 4801085.598874651,
        z: 3170177.394385061
      },
      duration: 2,
      orientation: {
        // 初始视角
        heading: 6.238757102061567,
        pitch: -0.5230891552682251,
        roll: 0.000030715561083027865,
      }
    });
  }

  /**
   * @description : 设备气象--小气象--每次点击大气象的时候
   */
  deviceMeteorological(val, type) {
    this.delete3D();
    let list = val;
    let list2 = []
    for (var i = 0; i < list.length; i++) {
      let str = null;
      let windDirection = "";
      if (list[i].windDirection === "EAST") windDirection = "东风";
      else if (list[i].windDirection === "WEST") windDirection = "西风";
      else if (list[i].windDirection === "SOUTH") windDirection = "南风";
      else if (list[i].windDirection === "NORTH") windDirection = "北风";
      else if (list[i].windDirection === "SOUTHWEST") windDirection = "西南风";
      else if (list[i].windDirection === "SOUTHEAST") windDirection = "东南风";
      else if (list[i].windDirection === "NORTHWEST") windDirection = "西北风";
      else if (list[i].windDirection === "NORTHEAST") windDirection = "东北风";
      if (type == 'WD') {
        str = list[i].airTemp + "℃";
      } else if (type == 'FL') {
        str = list[i].windSpeed + "km/h" + " " + windDirection + " " + list[i].windForce + '级';
      } else if (type == 'JS') {
        str = list[i].currentRainfall + "mm";
      }
      let point = new Cesium.Entity({
        // fromDegrees（经度，纬度，高度，椭球，结果）从以度为单位的经度和纬度值返回Cartesian3位置
        // position: Cesium.Cartesian3.fromDegrees(120.28317020626938, 30.331530552113783, 300),
        position: Cesium.Cartesian3.fromDegrees(parseFloat(list[i].gpsLng), parseFloat(list[i].gpsLat), 300),
        // billboard: {
        //   //这里需要改成您本地的路径的图片信息。
        //   image: list[i].icon,
        //   height: 30,
        //   width: 30,
        // },
        label: {
          text: str,
          font: '14px Source Han Sans CN',    //字体样式
          fillColor: Cesium.Color.WHITE,        //字体颜色
          backgroundColor: Cesium.Color.fromCssColorString('rgb(0, 133, 19)').withAlpha(0.8),    //背景颜色
          showBackground: true,                //是否显示背景颜色
          style: Cesium.LabelStyle.FILL,        //label样式
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,//垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,//水平位置
          pixelOffset: new Cesium.Cartesian2(20, 0)            //偏移
        }
      })
      viewer.entities.add(point);
      /* 设置相机位置 */
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(120.15416321882283, 30.255439142676586, 90000),
        duration: 2,
        orientation: {
          // 初始视角
          heading: 6.0908792936288245,
          pitch: -1.5659380609156122,
          roll: 0,
        },
      });
      list2.push(point)
    }
    return list2
  }

  /**
   * @description : 关闭小气象
   */
  closeDeviceMeteorological(val) {
    if (val.length === 0) return;
    val.forEach(item => {
      viewer.entities.remove(item)
    })
    /* 设置相机位置 */
    viewer.camera.flyTo({
      destination: {
        x: -2789575.5099842506,
        y: 4801085.598874651,
        z: 3170177.394385061
      },
      duration: 2,
      orientation: {
        // 初始视角
        heading: 6.238757102061567,
        pitch: -0.5230891552682251,
        roll: 0.000030715561083027865,
      }
    });
  }

  /**
   * @description : 风场
   */
  windyDraw(val) {
    let list = val;
    let list2 = [];
    for (var i = 0; i < list.length; i++) {
      let point = new Cesium.Entity({
        EntityType: "Wind",
        // fromDegrees（经度，纬度，高度，椭球，结果）从以度为单位的经度和纬度值返回Cartesian3位置
        position: Cesium.Cartesian3.fromDegrees(list[i].lon, list[i].lat, 300),
        billboard: {
          //这里需要改成您本地的路径的图片信息。
          image: import.meta.env.VITE_BASE_PUBLICPATH + '/img/windIcon.png',
          height: 34,
          width: 35,
          scale: 1.0,
          heightReference: 2,
          pixelOffset: new Cesium.Cartesian2(0, 1)
        },
        label: {
          type: "Wind",
          text: list[i].label + " " + list[i].windDir + " " + list[i].windLevel + "级",
          font: '14px Source Han Sans CN',    //字体样式
          fillColor: Cesium.Color.WHITE,        //字体颜色
          backgroundColor: Cesium.Color.fromCssColorString('rgb(0, 255, 102)').withAlpha(0.8),    //背景颜色
          showBackground: true,                //是否显示背景颜色
          style: Cesium.LabelStyle.FILL,        //label样式
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,//垂直位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,//水平位置
          pixelOffset: new Cesium.Cartesian2(17, 0)            //偏移
        }
      })
      viewer.entities.add(point);
      /* 设置相机位置 */
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(120.15416321882283, 30.255439142676586, 90000),
        duration: 2,
        orientation: {
          // 初始视角
          heading: 6.0908792936288245,
          pitch: -1.5659380609156122,
          roll: 0,
        },
      });
      // 禁用放大缩小和自由旋转视图
      // viewer.scene.screenSpaceCameraController.enableZoom = false;
      viewer.scene.screenSpaceCameraController.enableTilt = false;
      list2.push(point)
    }
    return list2
  }

  /**
   * @description : 关闭风场
   */
  closeWindDraw(val) {
    viewer.scene.screenSpaceCameraController.enableTilt = true;
    if (val.length === 0) return;
    val.forEach(item => {
      viewer.entities.remove(item)
    })
    /* 设置相机位置 */
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(120.13288996673643, 30.23966440052205, 2000),
      duration: 2,
      orientation: {
        // 初始视角
        heading: 6.238757149718078,
        pitch: -0.5230872963914144,
        roll: 0.0000306201637084
      }
    });
  }


  // ---------------------------------------  演示  ----------------------------------------------------------------
  exampleAirline() {
    /* 设置相机位置 */
    viewer.camera.flyTo({
      destination: {
        x: -2810015.1524538714,
        y: 4783030.53895414,
        z: 3168451.455425476
      },
      duration: 2,
      orientation: {
        // 初始视角
        heading: 6.111798546266149,
        pitch: -0.3822782065118975,
        roll: 0.00026584534823381745,
      }
    });

    let that = this
    let trackData1 = [
      // [120.2007294, 30.36576606, 1900],
      // [120.2137756, 30.35806393, 1800],
      // [120.2264786, 30.35036119, 1700],
      [120.2381516, 30.34265784, 1600],
      // [120.2508545, 30.33584283, 1500],
      [120.2642441, 30.32873101, 1400],
      // [120.2766037, 30.32102596, 1400],
      // [120.2906799, 30.31332031, 1300],
      [120.3033829, 30.30591045, 1200],
      // [120.3178024, 30.29850003, 1200],
      // [120.3298187, 30.2919784, 1200],
      // [120.3425217, 30.28545634, 1100],
      [120.3548813, 30.27834087, 1100],
      // [120.3682709, 30.27122488, 1000],
      [120.3820038, 30.26410837, 600],
    ]
    let trackData2 = [
      [120.3820038, 30.26410837, 600],
      [120.3957367, 30.25728791, 400],
      [120.4098129, 30.25046696, 200],
      [120.4221725, 30.2451285, 100],
      [120.4277515, 30.24394214, 0]
    ]

    let line = new Cesium.Entity({
      name: 'line',
      show: true,
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(trackData1.flat()),
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.fromCssColorString("#0f0").withAlpha(1),
        }),
        width: 15,
      },
    });

    let marker = new Cesium.Entity({
      position: Cesium.Cartesian3.fromDegrees(120.4120038, 30.28410837, 200),
      billboard: {
        //这里需要改成您本地的路径的图片信息。
        image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/UAVNormal.png",
        height: 47,
        width: 42,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      },
    })

    let property = new Cesium.SampledPositionProperty()
    let starttime = new Date()
    let stoptime
    let timestamp = starttime.getTime()
    trackData1.forEach((item, index) => {
      let time = new Date(timestamp + index * 2000)
      stoptime = time
      let position = Cesium.Cartesian3.fromDegrees(
        Number(item[0]), Number(item[1]), Number(item[2])
      )
      property.addSample(Cesium.JulianDate.fromDate(time), position)
    })
    property.setInterpolationOptions({
      interpolationDegree: 0.0001,
      interpolationAlgorithm: Cesium.LagrangePolynomialApproximation,
    })
    let entitydd = new Cesium.Entity({
      availability: new Cesium.TimeIntervalCollection([
        new Cesium.TimeInterval({
          start: Cesium.JulianDate.fromDate(starttime),
          stop: Cesium.JulianDate.fromDate(new Date(stoptime)),
        }),
      ]),
      // 点集
      position: property,
      // 朝向
      orientation: new Cesium.VelocityOrientationProperty(property),
      // 模型轮廓大小
      billboard: {
        image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/minghangFly.png", // 图像地址，URI或Canvas的属性
        width: 40, // 宽度（以像素为单位）
        height: 40, // 高度（以像素为单位）
        verticalOrigin: Cesium.VerticalOrigin.CENTER, // 相对于坐标的垂直位置
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 相对于坐标的水平位置
        show: true, // 是否显示
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      },
      // 飞行过的路径
      path: {
        leadTime: 0,
        resolution: 1,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.fromCssColorString("#0f0").withAlpha(1),
        }),
        width: 15,
      },
      viewFrom: new Cesium.Cartesian3(500, 500, 100), // 偏移量--设置视角高度
    })
    viewer.clock.currentTime = Cesium.JulianDate.fromDate(starttime) //修改时间轴的当前时间
    viewer.clock.stopTime = Cesium.JulianDate.fromDate(new Date(stoptime))
    viewer.clock.clockRange = Cesium.ClockRange.CLAMPED
    viewer.clock.shouldAnimate = true //开始播放
    viewer.entities.add(entitydd);
    viewer.entities.add(marker);

    // 创建时间线控件
    var timeline = new Cesium.Timeline(viewer.timeline.container, viewer.clock);

    // 监听轨迹回放结束事件
    let listen = function (clock) {
      if (clock.currentTime.equals(clock.stopTime)) {
        viewer.entities.add(line);
        that.drawScanCircle([120.4277515, 30.24394214, 0])
        marker = new Cesium.Entity({
          position: Cesium.Cartesian3.fromDegrees(120.4120038, 30.28410837, 200),
          billboard: {
            //这里需要改成您本地的路径的图片信息。
            image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/UAVNormalWarning.png",
            height: 47,
            width: 42,
            disableDepthTestDistance: Number.POSITIVE_INFINITY
          },
        })
        viewer.entities.add(marker);
        // 切换到下一段轨迹
        if (entitydd.position._property._times.length === trackData1.length) {

          let property = new Cesium.SampledPositionProperty()
          let starttime = new Date()
          let stoptime
          let timestamp = starttime.getTime()
          // 切换到轨迹数据2
          trackData2.forEach((item, index) => {
            let time = new Date(timestamp + index * 2000)
            stoptime = time
            let position = Cesium.Cartesian3.fromDegrees(
              Number(item[0]), Number(item[1]), Number(item[2])
            )
            property.addSample(Cesium.JulianDate.fromDate(time), position)
          })
          property.setInterpolationOptions({
            interpolationDegree: 0.0001,
            interpolationAlgorithm: Cesium.LagrangePolynomialApproximation,
          })
          entitydd = new Cesium.Entity({
            availability: new Cesium.TimeIntervalCollection([
              new Cesium.TimeInterval({
                start: Cesium.JulianDate.fromDate(starttime),
                stop: Cesium.JulianDate.fromDate(new Date(stoptime)),
              }),
            ]),
            // 点集
            position: property,
            // 朝向
            orientation: new Cesium.VelocityOrientationProperty(property),
            // 模型轮廓大小
            billboard: {
              image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/minghangFly.png", // 图像地址，URI或Canvas的属性
              width: 40, // 宽度（以像素为单位）
              height: 40, // 高度（以像素为单位）
              verticalOrigin: Cesium.VerticalOrigin.CENTER, // 相对于坐标的垂直位置
              horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 相对于坐标的水平位置
              show: true, // 是否显示
              disableDepthTestDistance: Number.POSITIVE_INFINITY
            },
            // 飞行过的路径
            path: {
              leadTime: 0,
              resolution: 1,
              material: new Cesium.PolylineGlowMaterialProperty({
                glowPower: 0.1,
                color: Cesium.Color.fromCssColorString("#0f0").withAlpha(1),
              }),
              width: 15,
            },
            viewFrom: new Cesium.Cartesian3(500, 500, 100), // 偏移量--设置视角高度
          })
          viewer.clock.currentTime = Cesium.JulianDate.fromDate(starttime) //修改时间轴的当前时间
          viewer.clock.stopTime = Cesium.JulianDate.fromDate(new Date(stoptime))
          viewer.clock.clockRange = Cesium.ClockRange.CLAMPED;
          viewer.clock.shouldAnimate = true //开始播放
          viewer.entities.add(entitydd);
          viewer.clock.onTick.removeEventListener(listen);
        }
      }
    }
    viewer.clock.onTick.addEventListener(listen);
  }


  /**
   * @description : 无人机侵入轨迹
   */
  noPeopleTrajectory() {
    // 绘制空域范围
    let str = {
      pointLocation: "120.282682,30.331923",
      radius: 4653,
      lowHeight: 1,
      topHeight: 600,
      fullColor: "#A5EFCD",
      EntityType: "airspace",
      airspaceId: "0e4b6d5265bb43e6a3d17e924df432d7"
    }
    let positions = str.pointLocation.split(",").map(Number)
    let circle = new Cesium.Entity({
      position: Cesium.Cartesian3.fromDegrees(...positions),

      ellipse: {
        semiMinorAxis: str.radius,
        semiMajorAxis: str.radius,
        height: str.lowHeight,
        extrudedHeight: str.topHeight,
        outline: false,
        // outlineWidth: 20,
        //   outlineColor: Cesium.Color.fromCssColorString(item.lineColor).withAlpha(1),
        material: Cesium.Color.fromCssColorString(str.fullColor).withAlpha(0.3),
      },
      EntityType: str.EntityType,
      id: str.airspaceId,
      cursorHand: true
    });

    viewer.entities.add(circle);

    //模型沿着轨迹移动（图标移动过的路径变色）
    let moveData = [{
      // time:1656047671018,
      x: 120.1949455286578,
      y: 30.324829192320514,
      z: 0
    }, {
      // time:1656047771018,
      x: 120.23528858903333,
      y: 30.320235969681377,
      z: 0
    }
    ];
    let moveData2 = [
      {
        // time:1656047771018,
        x: 120.23528858903333,
        y: 30.320235969681377,
        z: 0
      }, {
        // time:1656047871018,
        x: 120.26977750403564,
        y: 30.325588865040018,
        z: 0
      }, {
        // time:1656047971018,
        x: 120.24715490060731,
        y: 30.36020217526316,
        z: 0
      }
    ];
    let moveData3 = [
      {
        // time:1656047971018,
        x: 120.24715490060731,
        y: 30.36020217526316,
        z: 0
      }, {
        // time:1656048071018,
        x: 120.2121098679309,
        y: 30.37375625021542,
        z: 0
      }
    ]

    var date = new Date(moveData[0].time);
    var start = Cesium.JulianDate.fromDate(date); //获取第一个点的时间
    viewer.clock.startTime = start;  //将多个点的第一个点设为轨迹播放的开始时间
    viewer.clock.currentTime = start; //修改时间轴的当前时间
    viewer.clock.shouldAnimate = true; //开始播放
    for (var z = 0; z < moveData.length; z++) {
      var item = moveData[z];
      var thisTime = Cesium.JulianDate.fromDate(new Date(item.time));
      var position = Cesium.Cartesian3.fromDegrees(item.x, item.y, item.z);

      // 添加每一个链接点的信息，到达的时间以及坐标位置
      property.addSample(thisTime, position);
    }
    //设置贴地
    property.setInterpolationOptions({
      interpolationDegree: 2,
      interpolationAlgorithm: Cesium.LagrangePolynomialApproximation
    });

    var times = property._property._times;
    var startTime = times[0].clone();
    var stopTime = times[times.length - 1].clone();
    var entitydd = viewer.entities.add({ // 线动画
      availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
        start: startTime,
        stop: stopTime
      })]),
      position: property, // 点集
      model: {
        uri: '/3dTiles/model/drone.gltf',
        scale: 1,
        minimumPixelSize: 60
      },//model方式 和billboard二选一
      path: {
        leadTime: 0,
        resolution: 1,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.GREEN
        }),
        width: 10
      }
    })

  }


  noPeopleTrajectory2(changeCheck, clickWaringFunTrue, clickWaringFun) {
    changeCheckCockpit = changeCheck;
    clickWaringDis = clickWaringFun;
    clickWaringDisTrue = clickWaringFunTrue;
    // 绘制空域范围
    let str = {
      pointLocation: "120.282682,30.331923",
      radius: 4653,
      lowHeight: 1,
      topHeight: 600,
      fullColor: "#A5EFCD",
      EntityType: "airspace",
      airspaceId: "0e4b6d5265bb43e6a3d17e924df432d7"
    }
    let positions = str.pointLocation.split(",").map(Number)
    let circle = new Cesium.Entity({
      position: Cesium.Cartesian3.fromDegrees(...positions),

      ellipse: {
        semiMinorAxis: str.radius,
        semiMajorAxis: str.radius,
        height: str.lowHeight,
        extrudedHeight: str.topHeight,
        outline: false,
        // outlineWidth: 20,
        //   outlineColor: Cesium.Color.fromCssColorString(item.lineColor).withAlpha(1),
        material: Cesium.Color.fromCssColorString(str.fullColor).withAlpha(0.3),
      },
      // EntityType: str.EntityType,
      id: str.airspaceId,
      cursorHand: true
    });
    viewer.entities.add(circle);

    viewer.camera.flyTo({
      destination: {
        x: -2784418.783104299,
        y: 4770042.2682316685,
        z: 3187380.531451231
      },
      duration: 2,
      orientation: {
        // 初始视角
        heading: 6.235384067391087,
        pitch: -0.2120044740244278,
        roll: 0.000019625028013336987,
      }
    });

    //模型沿着轨迹移动（图标移动过的路径变色）
    let moveData = [{
      // time:1656047671018,
      longitude: 120.1949455286578,
      latitude: 30.324829192320514,
      height: 100
    }, {
      // time:1656047771018,
      longitude: 120.23528858903333,
      latitude: 30.320235969681377,
      height: 150
    }];
    let moveData2 = [
      {
        // time:1656047771018,
        longitude: 120.23528858903333,
        latitude: 30.320235969681377,
        height: 150
      }, {
        // time:1656047871018,
        longitude: 120.26977750403564,
        latitude: 30.325588865040018,
        height: 100
      }, {
        // time:1656047971018,
        longitude: 120.24715490060731,
        latitude: 30.36020217526316,
        height: 150
      }];
    let moveData3 = [
      {
        // time:1656047971018,
        longitude: 120.24715490060731,
        latitude: 30.36020217526316,
        height: 150
      }, {
        // time:1656048071018,
        longitude: 120.2121098679309,
        latitude: 30.37375625021542,
        height: 100
      }
    ]
    let currentDH = 1;
    let propertyA = new Cesium.SampledPositionProperty();
    let starttime = new Date()
    let stoptime;
    let timestamp = starttime.getTime()
    moveData.forEach((item, index) => {
      let time = new Date(timestamp + index * 2000)
      stoptime = time
      let position = Cesium.Cartesian3.fromDegrees(
        Number(item.longitude), Number(item.latitude), Number(item.height)
      )
      propertyA.addSample(Cesium.JulianDate.fromDate(time), position)
    })
    propertyA.setInterpolationOptions({
      interpolationDegree: 0.0001,
      interpolationAlgorithm: Cesium.LagrangePolynomialApproximation,
    })
    let entitydd = new Cesium.Entity({
      availability: new Cesium.TimeIntervalCollection([
        new Cesium.TimeInterval({
          start: Cesium.JulianDate.fromDate(starttime),
          stop: Cesium.JulianDate.fromDate(new Date(stoptime)),
        }),
      ]),
      // 点集
      position: propertyA,
      // 朝向
      orientation: new Cesium.VelocityOrientationProperty(propertyA),
      // 模型轮廓大小
      billboard: {
        image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/xyNormalFly.png", // 图像地址，URI或Canvas的属性
        width: 40, // 宽度（以像素为单位）
        height: 40, // 高度（以像素为单位）
        verticalOrigin: Cesium.VerticalOrigin.CENTER, // 相对于坐标的垂直位置
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 相对于坐标的水平位置
        show: true, // 是否显示
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      },
      // 飞行过的路径
      path: {
        leadTime: 0,
        resolution: 1,
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.fromCssColorString("#0f0").withAlpha(1),
        }),
        width: 15,
      },
      viewFrom: new Cesium.Cartesian3(500, 500, 100), // 偏移量--设置视角高度
    })
    viewer.clock.currentTime = Cesium.JulianDate.fromDate(starttime) //修改时间轴的当前时间
    viewer.clock.stopTime = Cesium.JulianDate.fromDate(new Date(stoptime))
    viewer.clock.clockRange = Cesium.ClockRange.CLAMPED
    viewer.clock.shouldAnimate = true //开始播放
    viewer.entities.add(entitydd);

    // 创建时间线控件
    var timeline = new Cesium.Timeline(viewer.timeline.container, viewer.clock);

    // 监听轨迹回放结束事件
    viewer.clock.onTick.addEventListener(function (clock) {
      if (clock.currentTime.equals(clock.stopTime)) {
        // 切换到下一段轨迹
        if (currentDH === 1) {
          changeCheckCockpit();
          clickWaringDisTrue();
          // 画第一段的线
          viewer.entities.add({ // 线动画
            polyline: {
              positions: Cesium.Cartesian3.fromDegreesArrayHeights([
                120.1949455286578, 30.324829192320514, 100,
                120.23528858903333, 30.320235969681377, 150
              ]),
              // 宽度
              width: 15,
              material: new Cesium.PolylineGlowMaterialProperty({
                glowPower: 0.1,
                color: Cesium.Color.fromCssColorString("#0f0").withAlpha(1),
              }),
              show: true, // 是否显示
              clampToGround: false, // 开启贴地
            },
          })

          let property = new Cesium.SampledPositionProperty()
          let starttime = new Date()
          let stoptime
          let timestamp = starttime.getTime()
          // 切换到轨迹数据2
          entitydd.position._property._times = [];
          entitydd.position._property._values = [];
          currentDH = 2;
          moveData2.forEach((item, index) => {
            let time = new Date(timestamp + index * 4000)
            stoptime = time
            let position = Cesium.Cartesian3.fromDegrees(
              Number(item.longitude), Number(item.latitude), Number(item.height)
            )
            property.addSample(Cesium.JulianDate.fromDate(time), position)
          })
          property.setInterpolationOptions({
            interpolationDegree: 0.0001,
            interpolationAlgorithm: Cesium.LagrangePolynomialApproximation,
          })
          entitydd = new Cesium.Entity({
            availability: new Cesium.TimeIntervalCollection([
              new Cesium.TimeInterval({
                start: Cesium.JulianDate.fromDate(starttime),
                stop: Cesium.JulianDate.fromDate(new Date(stoptime)),
              }),
            ]),
            // 点集
            position: property,
            // 朝向
            orientation: new Cesium.VelocityOrientationProperty(property),
            // 模型轮廓大小
            billboard: {
              image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/xyBlackFly.png", // 图像地址，URI或Canvas的属性
              width: 40, // 宽度（以像素为单位）
              height: 40, // 高度（以像素为单位）
              verticalOrigin: Cesium.VerticalOrigin.CENTER, // 相对于坐标的垂直位置
              horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 相对于坐标的水平位置
              show: true, // 是否显示
              disableDepthTestDistance: Number.POSITIVE_INFINITY
            },
            // 飞行过的路径
            path: {
              leadTime: 0,
              resolution: 1,
              material: new Cesium.PolylineGlowMaterialProperty({
                glowPower: 0.1,
                color: Cesium.Color.fromCssColorString("#f00").withAlpha(1),
              }),
              width: 15,
            },
            viewFrom: new Cesium.Cartesian3(500, 500, 100), // 偏移量--设置视角高度
          })
          viewer.clock.currentTime = Cesium.JulianDate.fromDate(starttime) //修改时间轴的当前时间
          viewer.clock.stopTime = Cesium.JulianDate.fromDate(new Date(stoptime))
          viewer.clock.clockRange = Cesium.ClockRange.CLAMPED;
          viewer.clock.shouldAnimate = true //开始播放
          viewer.entities.add(entitydd);
        } else if (currentDH === 2) {
          clickWaringDisTrue();
          // 画第一段的线
          viewer.entities.add({ // 线动画
            polyline: {
              positions: Cesium.Cartesian3.fromDegreesArrayHeights([
                120.23528858903333, 30.320235969681377, 150,
                120.26977750403564, 30.325588865040018, 100,
                120.24715490060731, 30.36020217526316, 150
              ]),
              // 宽度
              width: 15,
              material: new Cesium.PolylineGlowMaterialProperty({
                glowPower: 0.1,
                color: Cesium.Color.fromCssColorString("#f00").withAlpha(1),
              }),
              show: true, // 是否显示
              clampToGround: false, // 开启贴地
            },
          })

          let property = new Cesium.SampledPositionProperty()
          let starttime = new Date()
          let stoptime
          let timestamp = starttime.getTime()
          // 切换到轨迹数据2
          entitydd.position._property._times = [];
          entitydd.position._property._values = [];
          currentDH = null;
          moveData3.forEach((item, index) => {
            let time = new Date(timestamp + index * 4000)
            stoptime = time
            let position = Cesium.Cartesian3.fromDegrees(
              Number(item.longitude), Number(item.latitude), Number(item.height)
            )
            property.addSample(Cesium.JulianDate.fromDate(time), position)
          })
          property.setInterpolationOptions({
            interpolationDegree: 0.0001,
            interpolationAlgorithm: Cesium.LagrangePolynomialApproximation,
          })
          entitydd = new Cesium.Entity({
            availability: new Cesium.TimeIntervalCollection([
              new Cesium.TimeInterval({
                start: Cesium.JulianDate.fromDate(starttime),
                stop: Cesium.JulianDate.fromDate(new Date(stoptime)),
              }),
            ]),
            // 点集
            position: property,
            // 朝向
            orientation: new Cesium.VelocityOrientationProperty(property),
            // 模型轮廓大小
            billboard: {
              image: import.meta.env.VITE_BASE_PUBLICPATH + "/img/cockpit/xyNormalFly.png", // 图像地址，URI或Canvas的属性
              width: 40, // 宽度（以像素为单位）
              height: 40, // 高度（以像素为单位）
              verticalOrigin: Cesium.VerticalOrigin.CENTER, // 相对于坐标的垂直位置
              horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 相对于坐标的水平位置
              show: true, // 是否显示
              disableDepthTestDistance: Number.POSITIVE_INFINITY
            },
            // 飞行过的路径
            path: {
              leadTime: 0,
              resolution: 1,
              material: new Cesium.PolylineGlowMaterialProperty({
                glowPower: 0.1,
                color: Cesium.Color.fromCssColorString("#0f0").withAlpha(1),
              }),
              width: 15,
            },
            viewFrom: new Cesium.Cartesian3(500, 500, 100), // 偏移量--设置视角高度
          })
          viewer.clock.currentTime = Cesium.JulianDate.fromDate(starttime) //修改时间轴的当前时间
          viewer.clock.stopTime = Cesium.JulianDate.fromDate(new Date(stoptime))
          viewer.clock.clockRange = Cesium.ClockRange.CLAMPED;
          viewer.clock.shouldAnimate = true //开始播放
          viewer.entities.add(entitydd);
        }else {
          clickWaringFun();
          // viewer.entities.removeAll()
        }
      }
    });
  }
}
export default cesium